import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Spin, 
  Alert, 
  Button, 
  Row, 
  Col, 
  Tag, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  InputNumber,
  Switch,
  Popconfirm
} from 'antd';
import { 
  FaCogs, 
  FaPlay, 
  FaSync, 
  FaPlus,
  FaSearch,
  FaFilter
} from 'react-icons/fa';
import { motion } from 'framer-motion';
import { crawlerApi, ScheduledCrawlerTask } from '../../../services/crawlerApi';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';
import CustomCard from '../../../components/custom/CustomCard';
import type { ColumnsType } from 'antd/es/table';
import { notification } from '../../../components/common';

const { Option } = Select;

interface CreateTaskForm {
  name: string;
  description: string;
  cron_expression: string;
  crawler_type: string;
  project_name?: string;
  spider_name?: string;
  start_urls?: string;
  enabled: boolean;
}

const CrawlerSchedulerPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [tasks, setTasks] = useState<ScheduledCrawlerTask[]>([]);
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [createForm] = Form.useForm<CreateTaskForm>();

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [isAuthenticated, navigate]);

  // 获取定时任务列表
  useEffect(() => {
    const fetchTasks = async () => {
      try {
        setLoading(true);
        setError(null);
        
        const tasksData = await crawlerApi.getScheduledTasks(0, 100);
        setTasks(tasksData);
      } catch (err) {
        console.error('获取定时任务失败:', err);
        setError('获取定时任务失败: ' + (err instanceof Error ? err.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchTasks();
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 刷新任务列表
  const refreshTasks = async () => {
    try {
      setLoading(true);
      const tasksData = await crawlerApi.getScheduledTasks(0, 100);
      setTasks(tasksData);
    } catch (err) {
      notification.error({
        title: '刷新失败',
        message: '刷新失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    } finally {
      setLoading(false);
    }
  };

  // 创建定时任务
  const handleCreateTask = async (values: CreateTaskForm) => {
    try {
      setCreating(true);
      
      // 构建任务配置
      const taskConfig: Record<string, any> = {
        crawler_type: values.crawler_type
      };
      
      if (values.crawler_type === 'scrapyd') {
        if (!values.project_name || !values.spider_name) {
          notification.error({
            title: '任务配置错误',
            message: 'Scrapyd任务需要指定项目名称和爬虫名称'
          });
          return;
        }
        taskConfig.project_name = values.project_name;
        taskConfig.spider_name = values.spider_name;
      } else if (values.start_urls) {
        // 将start_urls字符串转换为数组
        const startUrls = values.start_urls
          .split('\n')
          .map(url => url.trim())
          .filter(url => url.length > 0);
        taskConfig.urls = startUrls;
      }
      
      await crawlerApi.createScheduledTask({
        name: values.name,
        description: values.description,
        cron_expression: values.cron_expression,
        task_config: taskConfig,
        enabled: values.enabled
      });
      
      notification.success({
        title: '任务创建',
        message: '定时任务创建成功'
      });
      setCreateModalVisible(false);
      createForm.resetFields();
      refreshTasks();
    } catch (err) {
      notification.error({
        title: '创建失败',
        message: '创建定时任务失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    } finally {
      setCreating(false);
    }
  };

  // 切换任务启用状态
  const toggleTaskStatus = async (taskId: number, enabled: boolean) => {
    try {
      notification.info({
        title: '功能待实现',
        message: '切换任务状态功能待实现'
      });
      // 这里需要实现更新任务状态的API调用
    } catch (err) {
      notification.error({
        title: '切换失败',
        message: '切换任务状态失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    }
  };

  // 删除任务
  const deleteTask = async (taskId: number) => {
    try {
      notification.info({
        title: '功能待实现',
        message: '删除任务功能待实现'
      });
      // 这里需要实现删除任务的API调用
      refreshTasks();
    } catch (err) {
      notification.error({
        title: '删除失败',
        message: '删除任务失败: ' + (err instanceof Error ? err.message : '未知错误')
      });
    }
  };

  // 获取状态标签颜色
  const getStatusColor = (enabled: boolean) => {
    return enabled ? 'success' : 'default';
  };

  // 表格列定义
  const columns: ColumnsType<ScheduledCrawlerTask> = [
    {
      title: '任务名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <span style={{ color: theme.textPrimary, fontWeight: 'bold' }}>{text}</span>
      )
    },
    {
      title: 'Cron表达式',
      dataIndex: 'cron_expression',
      key: 'cron_expression',
      render: (expression: string) => (
        <code style={{ 
          background: `rgba(${mode === 'dark' ? '97, 220, 163' : '24, 144, 255'}, 0.15)`,
          padding: '2px 6px',
          borderRadius: '4px',
          fontFamily: 'monospace',
          color: theme.textPrimary
        }}>
          {expression}
        </code>
      )
    },
    {
      title: '爬虫类型',
      dataIndex: 'task_config',
      key: 'crawler_type',
      render: (config: Record<string, any>) => {
        const type = config?.crawler_type || 'unknown';
        return (
          <Tag color={type === 'scrapy' ? 'blue' : type === 'scrapyd' ? 'green' : 'purple'}>
            {type}
          </Tag>
        );
      }
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      key: 'enabled',
      render: (enabled: boolean) => (
        <Tag color={getStatusColor(enabled)}>
          {enabled ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => new Date(date).toLocaleString()
    },
    {
      title: '下次执行',
      dataIndex: 'next_run_at',
      key: 'next_run_at',
      render: (date: string) => date ? new Date(date).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Switch
            checked={record.enabled}
            onChange={(checked) => toggleTaskStatus(record.id, checked)}
            checkedChildren="启用"
            unCheckedChildren="禁用"
          />
          <Button 
            type="primary" 
            size="small"
            icon={<FaPlay />}
            onClick={() => notification.info({
              title: '功能待实现',
              message: '立即执行功能待实现'
            })}
          >
            执行
          </Button>
          <Popconfirm
            title="确定要删除这个任务吗？"
            onConfirm={() => deleteTask(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              danger 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  // Cron表达式帮助文本
  const cronHelpText = (
    <div style={{ fontSize: '12px', marginTop: '4px', color: theme.textSecondary }}>
      <div>格式: 分 时 日 月 周</div>
      <div>例如: 0 0 * * * (每天0点执行)</div>
    </div>
  );

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <motion.div
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <div style={{ marginBottom: '24px' }}>
          <h1 style={{ 
            color: theme.glowColor, 
            fontSize: '28px',
            fontWeight: 'bold',
            marginBottom: '8px'
          }}>
            <FaCogs style={{ marginRight: '12px' }} />
            定时任务管理
          </h1>
          <p style={{ 
            fontSize: '16px',
            opacity: 0.8,
            marginBottom: '24px',
            color: theme.textSecondary
          }}>
            配置和管理定时爬虫任务
          </p>
        </div>

        {/* 操作栏 */}
        <div style={{ 
          marginBottom: '24px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          flexWrap: 'wrap',
          gap: '12px'
        }}>
          <div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button 
                type="primary" 
                icon={<FaPlus />}
                onClick={() => setCreateModalVisible(true)}
              >
                创建定时任务
              </Button>
            </motion.div>
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }} style={{ display: 'inline-block', marginLeft: '12px' }}>
              <Button 
                icon={<FaSync />}
                onClick={refreshTasks}
              >
                刷新
              </Button>
            </motion.div>
          </div>
          
          <div style={{ display: 'flex', gap: '12px' }}>
            <Input 
              placeholder="搜索任务..."
              prefix={<FaSearch style={{ color: theme.textSecondary }} />}
              style={{ width: '200px', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}` }}
            />
            <motion.div whileHover={{ scale: 1.05 }} whileTap={{ scale: 0.95 }}>
              <Button icon={<FaFilter />}>
                筛选
              </Button>
            </motion.div>
          </div>
        </div>

        {/* 任务列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5, delay: 0.2 }}
        >
          <CustomCard>
            {error ? (
              <Alert
                message="错误"
                description={error}
                type="error"
                showIcon
                style={{ marginBottom: '16px' }}
              />
            ) : null}
            
            {loading ? (
              <div style={{ textAlign: 'center', padding: '40px' }}>
                <Spin size="large" tip="加载中..." />
              </div>
            ) : (
              <CustomTable 
                dataSource={tasks}
                columns={columns}
                rowKey="id"
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  showQuickJumper: true
                }}
                locale={{
                  emptyText: (
                    <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                      <FaCogs style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                      <p>暂无定时任务</p>
                      <p style={{ fontSize: '14px' }}>
                        点击"创建定时任务"按钮开始创建定时任务
                      </p>
                    </div>
                  )
                }}
              />
            )}
          </CustomCard>
        </motion.div>

        {/* 创建定时任务模态框 */}
        <Modal
          title={
            <div style={{ display: 'flex', alignItems: 'center', color: theme.textPrimary }}>
              <FaPlus style={{ marginRight: '8px', color: theme.glowColor }} />
              创建定时任务
            </div>
          }
          open={createModalVisible}
          onCancel={() => {
            setCreateModalVisible(false);
            createForm.resetFields();
          }}
          onOk={() => createForm.submit()}
          confirmLoading={creating}
          width={600}
          styles={{ 
            body: { 
              background: theme.contentBackground,
              color: theme.textPrimary
            },
            header: {
              background: theme.cardBackground,
              borderBottom: `1px solid ${theme.cardBorder}`
            }
          }}
        >
          <Form
            form={createForm}
            layout="vertical"
            onFinish={handleCreateTask}
            initialValues={{ enabled: true }}
          >
            <Form.Item
              name="name"
              label={<span style={{ color: theme.textPrimary }}>任务名称</span>}
              rules={[{ required: true, message: '请输入任务名称' }]}
            >
              <Input 
                placeholder="请输入任务名称" 
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Form.Item
              name="description"
              label={<span style={{ color: theme.textPrimary }}>任务描述</span>}
            >
              <Input.TextArea 
                placeholder="请输入任务描述" 
                rows={3} 
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Form.Item
              name="cron_expression"
              label={<span style={{ color: theme.textPrimary }}>Cron表达式</span>}
              rules={[{ required: true, message: '请输入Cron表达式' }]}
              extra={cronHelpText}
            >
              <Input 
                placeholder="例如: 0 0 * * * (每天0点执行)" 
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              />
            </Form.Item>
            
            <Form.Item
              name="crawler_type"
              label={<span style={{ color: theme.textPrimary }}>爬虫类型</span>}
              rules={[{ required: true, message: '请选择爬虫类型' }]}
            >
              <Select 
                placeholder="请选择爬虫类型"
                style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
              >
                <Option value="scrapy">Scrapy</Option>
                <Option value="scrapyd">Scrapyd</Option>
                <Option value="mechanicalsoup">MechanicalSoup</Option>
              </Select>
            </Form.Item>
            
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, currentValues) => 
                prevValues.crawler_type !== currentValues.crawler_type
              }
            >
              {({ getFieldValue }) => {
                const crawlerType = getFieldValue('crawler_type');
                if (crawlerType === 'scrapyd') {
                  return (
                    <>
                      <Form.Item
                        name="project_name"
                        label={<span style={{ color: theme.textPrimary }}>项目名称</span>}
                        rules={[{ required: true, message: '请输入项目名称' }]}
                      >
                        <Input 
                          placeholder="请输入Scrapyd项目名称" 
                          style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                        />
                      </Form.Item>
                      <Form.Item
                        name="spider_name"
                        label={<span style={{ color: theme.textPrimary }}>爬虫名称</span>}
                        rules={[{ required: true, message: '请输入爬虫名称' }]}
                      >
                        <Input 
                          placeholder="请输入Scrapyd爬虫名称" 
                          style={{ background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                        />
                      </Form.Item>
                    </>
                  );
                } else if (crawlerType) {
                  return (
                    <Form.Item
                      name="start_urls"
                      label={<span style={{ color: theme.textPrimary }}>起始URLs</span>}
                      rules={[{ required: true, message: '请输入起始URLs，每行一个' }]}
                    >
                      <Input.TextArea 
                        placeholder="请输入起始URLs，每行一个" 
                        rows={4}
                        style={{ fontFamily: 'monospace', background: theme.cardBackground, border: `1px solid ${theme.cardBorder}`, color: theme.textPrimary }}
                      />
                    </Form.Item>
                  );
                }
                return null;
              }}
            </Form.Item>
            
            <Form.Item
              name="enabled"
              label={<span style={{ color: theme.textPrimary }}>启用状态</span>}
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
          </Form>
        </Modal>
      </motion.div>
    </div>
  );
};

export default CrawlerSchedulerPage;